package sms.impl;

import com.quanyan.common.utils.MD5Utils;
import com.quanyan.common.utils.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import sms.AbstractSmsApi;
import sms.model.Result;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 上海互亿
 * Created by zijun.song on 2015/7/1.
 */
public class HuyiSms extends AbstractSmsApi{

    private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

    private static final Log log = LogFactory.getLog(HuyiSms.class);


   private static Map<Byte,String> messageTemplate = new HashMap<Byte, String>();

   static{
       messageTemplate.put(MESSAGE_TEMPLATE_USER_BIND_PHONE,     "您的验证码是：【变量】，【变量】分钟内有效。");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_REGISTER,       "您的验证码是：【变量】，【变量】分钟内有效。");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_LOGIN ,         "您的验证码是：【变量】，【变量】分钟内有效。");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_REFUND,         "您的验证码是：【变量】，【变量】分钟内有效。");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_PASSWPRD_RECOVERY,"您正在找回密码,您的验证码是：【变量】，【变量】分钟内有效。");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_BINDING_YES,"您正在绑定支付账户,您的验证码是：【变量】，【变量】分钟内有效。");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_BINDING_NO,"您正在解绑支付账户,您的验证码是：【变量】，【变量】分钟内有效。");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_EXAMINE_YES,"恭喜您，您申请的【变量】达人已通过，请登录百灵鸟达人版发布活动，结识更多的百灵鸟小伙伴！");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_EXAMINE_NO,"很抱歉，您申请的【变量】达人未通过，【变量】，请登陆百灵鸟达人版更改信息!");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_REFUND_SMS,"您报名的【变量】活动已退款，退款金额【变量】元，1-3个工作日到账。订单号:【变量】。进入[我的活动]查看详情。");
       messageTemplate.put(MESSAGE_TEMPLATE_USER_REFUND_REJECT_SMS,"非常抱歉！您提交的退款申请已被拒绝；如有疑问，请与活动负责人【变量】联系；给您带来的不便，敬请谅解。");
       messageTemplate.put(MESSAGE_TEMPLATE_BATCH_REFUND_SMS,"非常抱歉！您参加的【变量】活动由于【变量】临时取消，您支付的款项和鸟蛋将会在1-3个工作日内退款至您的原支付渠道，退款到账日期以支付宝/微信支付为准， \n" +
               "如有疑问，请拨打客服电话【变量】。");
       messageTemplate.put(MESSAGE_TEMPLATE_SIGNUP_SMS,"感谢您参与【变量】，我们将在一周内完成审核，并告知您面试时间和地点，请保持手机畅通！快把好消息分享给小伙伴吧！");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ORDER_NOTICE,"您已成功预订【变量】场地：【变量】详情请咨询【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ORDER_TICKET_NOTICE,"您已成功预订【变量】门票：【变量】详情请咨询【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_REFUND_NOTICE,"您已成功退订【变量】场地：【变量】，退款将于三个工作日内返还。有疑问请致电【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_BALANCE_NOTICE,"您办理的【变量】的【变量】于【变量】通过调整【变量】元至【变量】元，有疑问请致电【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_CLUE_ACTIVITY_NOTICE,"您报名【变量】俱乐部的【变量】活动，已经报名成功，请在【变量】时间到【变量】地点参加，订单详情请点击百灵鸟安卓：【变量】，苹果iOS：【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_MEMBER_CONSUME_NOTICE,"您办理的【变量】的【变量】于【变量】通过【变量】消费了【变量】，卡内剩余【变量】,可登录百灵鸟客户端查看消费明细，如非本人操作，请立即致电【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ADD_MEMBER_INFO,"您于【变量】成功开通【变量】的【变量】,有疑问请致电【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ACTIVITY_NOTICE2,"您报名【变量】俱乐部的【变量】活动，已经报名成功，请在【变量】（开始时间）到【变量】（活动地址）地点参加，别迟到哟");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ORDER_REMIND,"客户：【变量】，通过客户端预定了【变量】场地：【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_OPERATIVE_AWARD_NOTICE,"铛铛铛，恭喜您获得百灵鸟送出的【变量】，请静候客服小妹联系您领取礼品噢!");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_PROMOTION_MESSAGE,"欢迎使用百灵鸟，请点击预订链接开始订场：【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_OPERATIVE_SNATCH_NOTICE,"报！您已成功在【变量】，详情猛戳【变量】，退订回T");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_ADD_MEMBER_REMIND,"客户：【变量】，在【变量】，通过APP办理了【变量】的【变量】，【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_PLACE_MEMBER_RECHARGE,"客户：【变量】，在【变量】，通过APP充值了【变量】的【变量】，【变量】");
       messageTemplate.put(MESSAGE_TEMPLATE_OPERATIVE_NEWYEAR_LOTTERY_NOTICE,"恭喜您，刚刚抽中了【变量】，百灵鸟工作人员将在7个工作日内通过电话或微信与您联系，请保持手机畅通！");
   }


    @Override
    protected String getTemplateByType(Byte id) {
        return messageTemplate.get(id);
    }

    @Override
    public Result sendMsg(String phone, Byte templateId, String[] args) {
        String content = getTemplateByType(templateId);
        for(int i = 1; i <= args.length ; i++){
            content = content.replaceFirst("【变量】", args[i - 1]);
        }
        return sendMsg(phone,content);
    }

    @Override
    public Result sendMsg(String[] phones, Byte templateId, String[] args) {
        return  new Result(false, Result.SMS_NOT_SUPPORT_PHONES, "暂不支持多个号码发送");
    }

    private Result sendMsg(String phone, String content) {
        Result result = Result.returnFail(Result.SMS_SEND_FAILURE);
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);
        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
        String password = "123456";
        String userName = "cf_quncao";
        try {
            NameValuePair[] data = {//提交短信
                    new NameValuePair("account", userName),
                    new NameValuePair("password", MD5Utils.MD5Encode(password)),
                    new NameValuePair("mobile", phone),
                    new NameValuePair("content", content),
            };

            method.setRequestBody(data);
            client.executeMethod(method);
            String SubmitResult = method.getResponseBodyAsString();
            log.info("send to " + phone + " message SubmitResult=> " + SubmitResult);
            String code="0";
            String msg="异常错误";
            if (!StringUtil.isBlankOrNull(SubmitResult)){//修复运营商bug,返回结果可能为空
                Document doc = DocumentHelper.parseText(SubmitResult);
                Element root = doc.getRootElement();
                code = root.elementText("code");
                msg = root.elementText("msg");
                String smsid = root.elementText("smsid");
                log.warn("send to " + phone + " message code=> " + code + ", msg=>" + msg + ", smsid=>" + smsid);
            }

            switch (Integer.parseInt(code)) {
                case 0:
                    result = Result.returnFail(Result.SMS_SEND_FAILURE);
                    break; //提交失败
                case 2:
                    result = Result.returnSuccess(Result.SMS_SEND_SUCCESS);
                    break; //提交成功
                case 403:
                case 406:
                    result = Result.returnFail(Result.INVALID_PHONE_NUMBER);
                    break; //手机号码非法
                case 4030:
                    result = Result.returnFail(Result.SMS_GATAWAI_LIMITED);
                    break;// 手机号码已被列入黑名单.
                case 407:
                    result = Result.returnFail(Result.INCLUDE_SENSITIVE_WORD);
                    break; //短信内容含有敏感词.
                default:
                    result = new Result(false, Integer.parseInt(code), msg);
                    break;
            }
            return result;
        } catch (HttpException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        } catch (DocumentException e) {
            log.error(e);
        }finally {
            method.releaseConnection();
        }
        return result;
    }


}
